package aerouacmsla.interfazDeUsuario;

import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import aerouacmsla.procedimientos.BDConexion;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
/**
 *
 * @author Marco
 */
public class VentanaInicioSesion extends javax.swing.JFrame {

    private BDConexion miConexion;

    public VentanaInicioSesion() {
        initComponents();
        setMiConexion(new BDConexion("localhost", "project_aerouac","root", "123456"));
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation(d.width / 2 - getSize().width / 2 , d.height / 2 - getSize().height / 2);
        MonitorDeConexion monitor = new MonitorDeConexion(getMiConexion());
        monitor.setVisible(true);
    }
    public VentanaInicioSesion(BDConexion miConexion) {
        initComponents();
        setMiConexion(miConexion);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation(d.width / 2 - getSize().width / 2 , d.height / 2 - getSize().height / 2);
        MonitorDeConexion monitor = new MonitorDeConexion(getMiConexion());
        monitor.setVisible(true);
    }

    public BDConexion getMiConexion() {
        return miConexion;
    }

    public void setMiConexion(BDConexion miConexion) {
        this.miConexion = miConexion;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        nombreDeUsuarioTextField = new javax.swing.JTextField();
        clavePasswordField = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        topPanel = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Iniciar Sesion");
        setIconImage(new ImageIcon(getClass().getResource("/Recursos/Icono32px.png")).getImage());
        setResizable(false);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        nombreDeUsuarioTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                nombreDeUsuarioTextFieldKeyPressed(evt);
            }
        });

        clavePasswordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                clavePasswordFieldKeyPressed(evt);
            }
        });

        jLabel1.setText("Nombre de Usuario");

        jLabel2.setText("Clave");

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/IconoLlaveSmall.png"))); // NOI18N

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/IconoUsuarioAnonimoSmall.png"))); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(clavePasswordField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
                    .addComponent(nombreDeUsuarioTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nombreDeUsuarioTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(clavePasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton1.setText("Iniciar Sesion");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        topPanel.setBackground(new java.awt.Color(51, 51, 51));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Inicio De Sesión");

        javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel);
        topPanel.setLayout(topPanelLayout);
        topPanelLayout.setHorizontalGroup(
            topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(topPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addContainerGap(305, Short.MAX_VALUE))
        );
        topPanelLayout.setVerticalGroup(
            topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(topPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addContainerGap(24, Short.MAX_VALUE))
        );

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 10));
        jLabel6.setText("Para el correcto funcionamiento un monitor debe haber iniciado sesion");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(topPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(54, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(5, 5, 5))
                    .addComponent(jButton1))
                .addGap(48, 48, 48))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6)
                .addContainerGap(115, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(topPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        int resultado = 0;
        String usuarioIngresado = nombreDeUsuarioTextField.getText();
        String claveIngresada = new String(clavePasswordField.getPassword());
        getMiConexion().sendSQLQuery("SELECT * FROM usuarios WHERE " +
        "nombre_usuario = '" + usuarioIngresado + "' && clave = '" + claveIngresada + "';");
        try {
            //Si devolvio un resultado se verifica el tipo de usuario
            if (getMiConexion().getResultado().next()) {
                resultado = Integer.parseInt(getMiConexion().getResultado().getObject("id_cargo").toString());
                String claveRecuperada = getMiConexion().getResultado().getObject("clave").toString();
                if (!claveRecuperada.equals(claveIngresada)) resultado = 3;
                String nombreUsuario = getMiConexion().getResultado().getObject("nombre_usuario").toString();
                String nombreClave = getMiConexion().getResultado().getObject("nombre").toString();
                nombreClave += " " + getMiConexion().getResultado().getObject("apellido_paterno").toString();
                nombreClave += " " + getMiConexion().getResultado().getObject("apellido_materno").toString();
                switch (resultado){
                    //usuario monitor
                    case 3:
                        DialogoCiudades obtenerId = new DialogoCiudades(getMiConexion());
                        obtenerId.setVisible(true);
                        VentanaMonitor ventanaMonitor = new VentanaMonitor(getMiConexion(), obtenerId.getId(), this);
                        this.setVisible(false);
                        ventanaMonitor.setVisible(true);
                        break;
                    //Administrador
                    case 1: 
                        VentanaAdministracion ventanaAdministracion = new VentanaAdministracion(this, getMiConexion(), nombreUsuario);
                        this.setVisible(false);
                        ventanaAdministracion.setVisible(true);
                        break;
                    //Usuario
                    case 2:
                        VentanaUsuario ventanaUsuario = new VentanaUsuario(this, getMiConexion(), nombreClave, nombreUsuario);
                        this.setVisible(false);
                        ventanaUsuario.setVisible(true);
                        break;
                    default:
                        JOptionPane.showMessageDialog(this,
                        "La clave que ha ingresado es incorrecta.",
                        "Clave Incorrecta",
                        JOptionPane.ERROR_MESSAGE); //contraseña erronea
                }
            }
            else JOptionPane.showMessageDialog(this,
                 "Compruebe que los datos ingresados sean correctos.",
                 "Compruebe los Datos",
                 JOptionPane.ERROR_MESSAGE);
        } catch (SQLException ex) {
            Logger.getLogger(VentanaInicioSesion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1MouseClicked

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        nombreDeUsuarioTextField.setText("");
        clavePasswordField.setText("");
    }//GEN-LAST:event_formComponentShown

    private void clavePasswordFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_clavePasswordFieldKeyPressed
       if (KeyEvent.VK_ENTER == evt.getKeyCode()){
           jButton1MouseClicked(null);
       }
    }//GEN-LAST:event_clavePasswordFieldKeyPressed

    private void nombreDeUsuarioTextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nombreDeUsuarioTextFieldKeyPressed
       if (KeyEvent.VK_ENTER == evt.getKeyCode()){
           jButton1MouseClicked(null);
       }
    }//GEN-LAST:event_nombreDeUsuarioTextFieldKeyPressed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaInicioSesion().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPasswordField clavePasswordField;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField nombreDeUsuarioTextField;
    private javax.swing.JPanel topPanel;
    // End of variables declaration//GEN-END:variables

}
